﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace KeyboardCount
{
    class DateRecord
    {
        public void SerializeRecord(DateTime day, keys daykey)
        {
            string path = Application.StartupPath + "\\DataRecord\\";
            path += day.Year.ToString() + "-" + day.Month.ToString() + "-" + day.Day.ToString() + ".dat";
            FileStream file = new FileStream(path, FileMode.Create);
            BinaryFormatter b = new BinaryFormatter();
            b.Serialize(file, daykey);
            file.Close();
        }

        public keys DeserializeRecord(DateTime day, keys daykey)
        {
            string path = Application.StartupPath + "\\DataRecord\\";
            path += day.Year.ToString() + "-" + day.Month.ToString() + "-" + day.Day.ToString() + ".dat";
            if (File.Exists(path))
            {
                FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryFormatter b = new BinaryFormatter();
                daykey = b.Deserialize(file) as keys;
                file.Close();
            } 
            else
            {
                SerializeRecord(day, daykey);
            }
            return daykey;
        }

        public keys CheckNextDay(keys daykey)
        {
            DateTime day = DateTime.Now;
            string path = Application.StartupPath + "\\DataRecord\\";
            path += day.Year.ToString() + "-" + day.Month.ToString() + "-" + day.Day.ToString() + ".dat";
            if (!File.Exists(path))
            {
                DateTime Lastday = day.AddDays(-1);
                SerializeRecord(Lastday, daykey);
                daykey = new keys();
            }
            SerializeRecord(day, daykey);
            return daykey;
        }
    }
}
